package com.hunlian.makelove.net;

import android.content.Context;
import android.os.Build;
import android.webkit.WebSettings;

import com.hunlian.makelove.AppApplication;
import com.hunlian.makelove.tools.AesEncryptionUtil;
import com.hunlian.makelove.tools.LogTools;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Subscriber;


public class RequestHttp {



	public void postVisit(final Context context, String url, JSONObject paramter,
						  final StringResponseCallbackListener callback){

		try {
			LogTools.e("加密前："+paramter.toString());
			//对参数进行AES加密
			final String ecryptParamter = AesEncryptionUtil.encrypt(paramter.toString(),AesEncryptionUtil.Password,AesEncryptionUtil.Iv);
			//LogTools.e("加密后："+ecryptParamter);

			FormBody.Builder builder = new FormBody.Builder();
			builder.add("data",ecryptParamter);
			RequestBody formBody = builder.build();

			final Request request = addHeaders(context).url(url).post(formBody).build();
			final Call call = CustomerOkHttpClient.getClient().newCall(request);
			call.enqueue(new Callback() {
				@Override
				public void onFailure(Call call, IOException e) {
					if(callback != null){
						callback.onFailure("",e.getMessage(),null);
					}
				}

				@Override
				public void onResponse(Call call, okhttp3.Response response) throws IOException {
					//LogTools.e("response: " + response.body().string());
					if(callback != null){
						//只是成功得到了返回，但不代表返回的是正确数据——有可能是接口定义的错误返回
						//不同的应用可能对正确、错误数据定义不一样，所以需要到具体的应用里分解(正确与错误)数据


						//对返回的json进行AES解密
						final String decryptSring = AesEncryptionUtil.decrypt(response.body().string(),AesEncryptionUtil.Password,AesEncryptionUtil.Iv);
						//String decryptSring = new String(Base64.decode(arg0.toString(), Base64.DEFAULT));
						//System.out.println("decryptSring: "+decryptSring);

						CustomerOkHttpClient.okHttpHandler.post(new Runnable() {
							@Override
							public void run() {
								callback.onSuccess(decryptSring);
							}
						});

					}

				}

			});

		} catch (Exception e) {

		}
	}


	public Observable<String> postVisit(final Context context, final String url, final JSONObject paramter){
		return Observable.create(new Observable.OnSubscribe<String>() {
			@Override
			public void call(final Subscriber<? super String> subscriber) {
				try {
					LogTools.e("加密前："+paramter.toString());
					//对参数进行AES加密
					final String ecryptParamter = AesEncryptionUtil.encrypt(paramter.toString(),AesEncryptionUtil.Password,AesEncryptionUtil.Iv);
					//LogTools.e("加密后："+ecryptParamter);

					FormBody.Builder builder = new FormBody.Builder();
					builder.add("data",ecryptParamter);
					RequestBody formBody = builder.build();

					final Request request = addHeaders(context).url(url).post(formBody).build();
					final Call call = CustomerOkHttpClient.getClient().newCall(request);
					call.enqueue(new Callback() {
						@Override
						public void onFailure(Call call, IOException e) {
							subscriber.onError(e);
						}

						@Override
						public void onResponse(Call call, okhttp3.Response response) throws IOException {
							//LogTools.e("response: " + response.body().string());
							if(response.isSuccessful()){
								//只是成功得到了返回，但不代表返回的是正确数据——有可能是接口定义的错误返回
								//不同的应用可能对正确、错误数据定义不一样，所以需要到具体的应用里分解(正确与错误)数据


								//对返回的json进行AES解密
								final String decryptSring = AesEncryptionUtil.decrypt(response.body().string(),AesEncryptionUtil.Password,AesEncryptionUtil.Iv);
								//String decryptSring = new String(Base64.decode(arg0.toString(), Base64.DEFAULT));
								//System.out.println("decryptSring: "+decryptSring);

								CustomerOkHttpClient.okHttpHandler.post(new Runnable() {
									@Override
									public void run() {
										subscriber.onNext(decryptSring);
									}
								});
							}
						}

					});

				} catch (Exception e) {

				}
			}
		});
	}



	/**
	 * 统一为请求添加头信息
	 * @return
	 */
	private Request.Builder addHeaders(Context context) {
		Request.Builder builder = new Request.Builder()
				.removeHeader("user-agent")
				.addHeader("user-agent",getUserAgent())
				.addHeader("Connection", "keep-alive")
				.addHeader("platform", "android")// 手机系统平台
				.addHeader("phoneModel", Build.MODEL)// 手机型号
				.addHeader("systemVersion", Build.VERSION.RELEASE)// 手机系统版本
				.addHeader("appVersion", BaseUtil.getAppUtils().getPackageInfo(context).versionName + '#'
						+ BaseUtil.getAppUtils().getPackageInfo(context).versionCode);// App版本
		return builder;
	}

	private  String getUserAgent() {
		String userAgent = "";
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
			try {
				userAgent = WebSettings.getDefaultUserAgent(AppApplication.getAppContext());
			} catch (Exception e) {
				userAgent = System.getProperty("http.agent");
			}
		} else {
			userAgent = System.getProperty("http.agent");
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0, length = userAgent.length(); i < length; i++) {
			char c = userAgent.charAt(i);
			if (c <= '\u001f' || c >= '\u007f') {
				sb.append(String.format("\\u%04x", (int) c));
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

}
